#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

typedef struct Song {
    char name[100];
    char artist[50];
    int duration;
    struct Song *next;
} Song;


typedef struct {
    Song *head;
    Song *tail;
    int count;
} Playlist;


typedef struct {
    Song **songs;
    int front;
    int rear;
    int capacity;
    int size;
    int is_random;
    int current;
} PlayerQueue;


void init_player_queue(PlayerQueue *queue, int capacity) {
    queue->songs = (Song**)malloc(capacity * sizeof(Song*));
    queue->capacity = capacity;
    queue->front = queue->rear = queue->size = 0;
    queue->is_random = 0;
    queue->current = -1;
}


void load_to_queue(PlayerQueue *queue, Playlist *playlist) {
    int i = 0;
    if (queue->is_random) {

        Song **temp = (Song**)malloc(playlist->count * sizeof(Song*));
        Song *curr = playlist->head;


        for ( i = 0; curr; i++, curr = curr->next) {
            temp[i] = curr;
        }


        srand(time(NULL));
        for ( i = playlist->count - 1; i > 0; i--) {
            int j = rand() % (i + 1);
            Song *tmp = temp[i];
            temp[i] = temp[j];
            temp[j] = tmp;
        }


        queue->size = 0;
        for ( i = 0; i < playlist->count && i < queue->capacity; i++) {
            queue->songs[queue->rear] = temp[i];
            queue->rear = (queue->rear + 1) % queue->capacity;
            queue->size++;
        }

        free(temp);
    } else {

        queue->size = 0;
        Song *curr = playlist->head;
        if (curr && queue->size < queue->capacity) {
            queue->songs[queue->rear] = curr;
            queue->rear = (queue->rear + 1) % queue->capacity;
            queue->size++;
            curr = curr->next;
        }
    }
    queue->current = queue->front;
}


Song* play_next(PlayerQueue *queue) {
    if (queue->size == 0) return NULL;

    if (queue->current == -1) {
        queue->current = queue->front;
    } else {
        queue->current = (queue->current + 1) % queue->capacity;
        if (queue->current == queue->rear) {
            queue->current = queue->front;
        }
    }
    return queue->songs[queue->current];
}

Song* play_current(PlayerQueue *queue)
{
    if (queue->size == 0 || queue->current == -1)
        return NULL;

    return queue->songs[queue->current];

}

Song* play_prev(PlayerQueue *queue) {
    if (queue->size == 0) return NULL;

    if (queue->current == -1) {
        queue->current = (queue->rear - 1 + queue->capacity) % queue->capacity;
    } else {
        queue->current = (queue->current - 1 + queue->capacity) % queue->capacity;
        if (queue->current == (queue->front - 1 + queue->capacity) % queue->capacity) {
            queue->current = (queue->rear - 1 + queue->capacity) % queue->capacity;
        }
    }
    return queue->songs[queue->current];
}
